import { useState } from 'react';
import { Modal, Button, Spin, Switch } from 'antd';
import { PDFDownloadLink, BlobProvider } from '@react-pdf/renderer';
import StoreReportPDF from './contents/ContentPDF';
import styles from './style.module.scss';


const PdfExporter = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [generateDate, setGenerateDate] = useState('');
  const [wmSwitch, setWmSwitch] = useState(true);


  const [docKey, setDocKey] = useState(Date.now());

  // 切换水印时重置文档实例
  const handleWmSwitch = (checked: boolean) => {
    setWmSwitch(checked);
    setDocKey(Date.now()); // 通过改变 key 强制重新挂载组件
  };


  const handlePreview = () => {
    setGenerateDate(new Date().toLocaleString());
    setModalVisible(true);
  };


  return (
    <>
      <div className={styles.actionButtons}>
        <Button type="primary" onClick={handlePreview}>
          预览PDF
        </Button>

        <PDFDownloadLink
          key={docKey}  // 通过 key 强制重新创建实例
          document={<StoreReportPDF generateDate={generateDate} wmSwitch={wmSwitch} />}
          fileName="门店对比分析报告.pdf"
        >
          <Button
            type="primary"
            onClick={() => setGenerateDate(new Date().toLocaleString())}
          >
            导出PDF
          </Button>
        </PDFDownloadLink>

        <div className={styles.watermarkText}>
          <h6>水印</h6>
          <Switch checked={wmSwitch} onChange={handleWmSwitch} />
        </div>
      </div>

      <Modal
        title="PDF预览"
        width={800}
        className={styles.previewModal}
        footer={null}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
      >
        <BlobProvider
          key={docKey}  // 通过 key 强制重新创建实例
          document={<StoreReportPDF generateDate={generateDate} wmSwitch={wmSwitch} />}
        >
          {({ url, loading }) => (
            loading ? (
              <div className={styles.loadingContainer}>
                <Spin tip="生成中...">
                  <div style={{ height: 100 }} />
                </Spin>
              </div>
            ) : (
              <iframe
                className={styles.pdfPreview}
                src={`${url}#view=FitH`}
              />
            )
          )}
        </BlobProvider>
      </Modal>
    </>
  );
};

export default PdfExporter;